package com.pms.web;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.service.ICameraUserInformationService;
import com.pms.service.IIotAgencyService;
import com.pms.util.FluoriteCloudUtile;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.pms.controller.BaseController;
import com.pms.service.IIotEqCameraService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/iotEqCamera")
@Api(value="二汞摄像头列表",description = "二汞摄像头列表")
public class IotEqCameraController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IIotEqCameraService iotEqCameraService;
    @Autowired
    private com.pms.cache.utils.RedisCacheUtil RedisCacheUtil;
    @Autowired
    private ICameraUserInformationService service;
    @Autowired
    IIotAgencyService orgService;

    /**
     * 添加摄像头
     * @param key
     * @param verificationCode
     * @param place
     * @param agencyId
     * @param communityId
     * @param belongedAgencyId
     * @param remack
     * @param companyCode
     * @return
     * @throws Exception
     */
    @PostMapping("/add/camera")
    @ApiOperation("添加摄像头")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "设备序列号", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "verificationCode", value = "验证码", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "place", value = "摄像头位置", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "agencyId", value = "水泵房ID", required = true, dataType = "Long", paramType = "form"),
            @ApiImplicitParam(name = "communityId", value = "所属小区ID", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "belongedAgencyId", value = "所属物业ID", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "remack", value = "简介", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "companyCode", value = "系统编码", required = true, dataType = "String", paramType = "form"),
           })
    public R addCamera(String key, String verificationCode, String place, Long agencyId,String communityId,String belongedAgencyId,String  remack
    ,String companyCode) throws Exception {
        Assert.isNull(key,"序列号key不能为空");
        Assert.isNull(verificationCode,"验证码verificationCode不能为空");
        Assert.isNull(place,"摄像头名称place不能为空");
        Assert.isNull(agencyId,"水泵房ID不能为空");
        Assert.isNull(communityId,"所属小区不能为空");
        Assert.isNull(belongedAgencyId,"所属物业不能为空");
        parameterIsNull(companyCode,"请填写系统编码");
        IotAgency iotAgency= orgService.selectById(agencyId);
        Assert.isNull(iotAgency,"该水泵房信息不存在");
        if (iotAgency.getLevel()!=4){return  R.error(400,"该机构ID不属于水泵房ID");}
        IotEqCamera eq =new IotEqCamera();
        IotAgency  belongedAgency = orgService.selectById(belongedAgencyId);
        parameterIsNull(iotAgency,"物业信息不存在");
        IotAgency  parentAgency = orgService.selectById(iotAgency.getParentId());//查询父级
        parameterIsNull(parentAgency,"小区机构信息不存在");
        eq.setBelongedHouse(iotAgency.getName());//水泵房名称
        eq.setFrontAddress("1");
        eq.setAgencyId(iotAgency.getId());//水泵房ID
        eq.setBelongedAgency(belongedAgency.getName());//物业
        eq.setSpId(belongedAgency.getId());//物业
        eq.setBelongedCommunity(parentAgency.getName());//小区
        eq.setCommunityId(parentAgency.getId());//小区
        eq.setCompanyCode(companyCode);
        eq.setRemack(remack);
        eq.setKey(key);//序列号
        eq.setVerificationCode(verificationCode);//验证码
        eq.setPlace(place);//位置
        eq.setCreateBy(getCurrentUserMap().get("userName"));
        eq.setCreateTime(new Date());//创建时间
        eq.setCurrentdateTime(new Date());//当前时间
        List<CameraUserInformation> camerauser = service.selectList(new EntityWrapper<CameraUserInformation>().lt("sum_",10));//查询所有摄像头sum不足10个
        if(camerauser.size()!=0||null!=camerauser ||!camerauser.isEmpty()){
            eq.setCameraUserId(camerauser.get(0).getId());
            CameraUserInformation cu=service.selectById(camerauser.get(0).getId());
            JSONObject json = FluoriteCloudUtile.fluoriteCloud1(cu.getAppkey(),cu.getAppsecret());
            String code = json.getString("code");
            if(code.equals("200")){
                String data = json.getString("data");
                if(StringUtils.isNotEmpty(data)){
                    JSONObject jsonResult = JSON.parseObject(data);
                    String accessToken = jsonResult.getString("accessToken");//token码
                    String expireTime = jsonResult.getString("expireTime");//结束时间
                    eq.setToken(accessToken);//保存token码
                    try{
                        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Long time=new Long(expireTime);
                        String d = format.format(time);//时间戳转换成标准时间
                        Date  e = format.parse(d);     //标准时间转换成国际时间
                        Calendar cal = Calendar.getInstance();//使用默认时区和语言环境获得一个日历
                        cal.setTime(e);
                        cal.add(Calendar.DATE, -1);  //结束时间减1天
                        eq.setExpireTime(format.parse(format.format(cal.getTime())));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            JSONObject cloud =new JSONObject();
            cloud = FluoriteCloudUtile.addfluoriteCloud(eq.getKey(), eq.getVerificationCode(),eq.getToken());
            String code1=cloud.getString("code");
            if(code1.equals("200")){
                JSONObject capture = FluoriteCloudUtile.capture(eq.getKey(),"1",eq.getToken());
                if(capture.getString("code").equals("200")){
                    JSONObject data= capture.getJSONObject("data");
                    Object img=data.get("picUrl");
                    eq.setPicurl(img.toString());
                    RedisCacheUtil.saveAndUpdate("PhotoCapture"+eq.getEqId(), img,10);
                }
                iotEqCameraService.insert(eq);
                cu.setSum(cu.getSum()+1);
                service.updateAllColumnById(cu);//修改总数
                return R.ok();
            }else{
               return R.error(Integer.parseInt(cloud.get("code").toString()),cloud.get("msg").toString());
            }
        }else{
            throw new RRException("对不起没有可用用户配置信息，请联系管理员",400);
        }
    }

    /**
     * 修改摄像头
     * @param eqId
     * @param agencyId
     * @param place
     * @param belongedHouse
     * @param communityId
     * @param belongedAgencyId
     * @param remack
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改摄像头")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "eqId", value = "摄像头ID", required = true, dataType = "Long", paramType = "form"),
            @ApiImplicitParam(name = "place", value = "摄像头位置", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "agencyId", value = "水泵房ID", required = false, dataType = "Long", paramType = "form"),
            @ApiImplicitParam(name = "belongedHouse", value = "所属水泵房", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "communityId", value = "所属小区ID", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "belongedAgencyId", value = "所属物业ID", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "remack", value = "简介", required = false, dataType = "String", paramType = "form"),
    })
    public R update(Long eqId,Long agencyId,String place,String belongedHouse,String communityId,String belongedAgencyId,String remack){
        Assert.isNull(eqId," 摄像头设备ID不能为空");
        IotEqCamera eq= iotEqCameraService.selectById(eqId);
        Assert.isNull(eq," 该摄像头信息不存在");
        IotAgency iotAgency= orgService.selectById(agencyId);
        Assert.isNull(iotAgency,"该水泵房信息不存在");
        if (iotAgency.getLevel()!=4){return  R.error(400,"该机构ID不属于水泵房ID");}
        if (StringUtils.isNotEmpty(place)){
            eq.setPlace(place);
        }
        if (agencyId!=null){
            eq.setAgencyId(agencyId);
        }
        if (StringUtils.isNotBlank(belongedHouse)){
            eq.setBelongedHouse(iotAgency.getName());
            eq.setAgencyId(agencyId);
        }
        if (StringUtils.isNotBlank(communityId)){
            IotAgency  parentAgency = orgService.selectById(communityId);//查询父级
            parameterIsNull(parentAgency,"小区机构信息不存在");
            eq.setBelongedCommunity(parentAgency.getName());
            eq.setCommunityId(Long.parseLong(communityId));
        }
        if (StringUtils.isNotBlank(belongedAgencyId)){
            IotAgency  belongedAgency = orgService.selectById(belongedAgencyId);
            parameterIsNull(iotAgency,"物业信息不存在");
            eq.setBelongedAgency(belongedAgency.getName());
            eq.setSpId(Long.parseLong(belongedAgencyId));
        }
        if (StringUtils.isNotBlank(remack)){
            eq.setRemack(remack);
        }
        iotEqCameraService.updateById(eq);
        return R.ok();
    }
    /**
     * 删除摄像头
     * @param eqId
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除摄像头")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "eqId", value = "摄像头ID", required = true, dataType = "Long", paramType = "form"),
    })
    public R delete(Long eqId){
        Assert.isNull(eqId," 设备ID不能为空");
        IotEqCamera eq= iotEqCameraService.selectById(eqId);
        Assert.isNull(eq," 该摄像头信息不存在");
        JSONObject cloud = FluoriteCloudUtile.deletefluoriteCloud(eq.getKey(),eq.getToken());
        if(cloud.getString("code").equals("200")){
            CameraUserInformation user=service.selectById(eq.getCameraUserId());
            Assert.isNull(user,"该摄像头用户配置信息不存在");
            user.setSum(user.getSum()-1);
            service.updateAllColumnById(user);
            iotEqCameraService.deleteById(eq.getEqId());
            return R.ok();
        }else{
            return R.error(Integer.parseInt(cloud.get("code").toString()),cloud.get("msg").toString());
        }
    }

    /**
     * 查询单条摄像头信息
     * @param eqId
     * @return
     */
    @GetMapping("/findById")
    @ApiOperation(value = "查询单条摄像头信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "eqId", value = "摄像头ID", required = true, dataType = "Long", paramType = "form"),
    })
    public R findById(Long eqId){
        Assert.isNull(eqId," 设备ID不能为空");
        IotEqCamera eq= iotEqCameraService.selectById(eqId);
        return R.ok().put("data",eq);
    }

    /**
     * 分页查询摄像头
     * @param limit
     * @param page
     * @param name
     * @param agencyId
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询摄像头")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "limit", value = "条数", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "name", value = "", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "agencyId", value = "水泵房ID", required = true, dataType = "Long", paramType = "form"),
            @ApiImplicitParam(name="target",value="标识查询层级（1查询水泵房2查询物业小区3查询系统）",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="companyCode",value="公司编码",required = true,dataType = "String",paramType="form"),
    })
    public R page(int limit,int page,String name,String agencyId,int target,String companyCode){
        parameterIsNull(agencyId,"水泵组ID不能为空");
        parameterIsNull(target,"标识是否是水泵组");
        parameterIsNull(companyCode,"请填写公司编码");
        if (limit<1){limit=10;}
        if (page<1){page=1;}
        Page<IotEqCamera> pages = new Page<>(page,limit);
        Wrapper<IotEqCamera> ew=new EntityWrapper();
        if (target==1){
            ew.eq("agency_id",agencyId);//查询水泵房
        }else if ((target==2)){
            IotAgency  agency = orgService.selectById(agencyId);
            parameterIsNull(agency,"机构信息不存在");
            if (agency.getLevel()==2){
                ew.eq("sp_id",agencyId);//查询物业
            }else if (agency.getLevel()==3){
                ew.eq("community_id",agencyId);//查询小区
            }
        }else  if (target==3){
            ew.eq("company_code",companyCode);//查询系统
        }else{
            return  R.error(400,"参数异常");
        }
        if (StringUtils.isNotBlank(name)){
            ew.and().like("place_",name);
            ew.or().like("key_",name);
            ew.or().like("remack_",name);
            ew.or().like("belonged_house",name);
            ew.or().like("belonged_community",name);
            ew.or().like("belonged_agency",name);
        }
        Page<IotEqCamera> pageList = iotEqCameraService.selectPage(pages,ew);
        return  R.ok().put("data",pageList);
       }

}